package vn.mobiistar.videoapp.fragment;

import java.util.ArrayList;

import vn.appsmobi.loader.Pager;
import vn.mobiistar.videoapp.R;
import vn.mobiistar.videoapp.activity.MainActivity;
import vn.mobiistar.videoapp.loader.BaseLoader;
import vn.mobiistar.videoapp.loader.BaseResult;
import vn.mobiistar.videoapp.loader.VideoLoader;
import vn.mobiistar.videoapp.other.Category;
import vn.mobiistar.videoapp.other.Define;
import vn.mobiistar.videoapp.other.Video;
import vn.mobiistar.videoapp.other.VideoPlayer;
import vn.mobiistar.videoapp.ui.BlockView;
import vn.mobiistar.videoapp.ui.Refreshable;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.github.pedrovgs.DraggablePanel;

public class CategoryVideoListFragment extends BaseFragment implements
		LoaderCallbacks<BaseResult>, Refreshable {

	private static final long DELAY_MILLIS = 10;
	public Context mContext;
	public ArrayList<Video> mData;
	public BaseLoader mLoaderList; 
	public boolean mIsReachedBottom;
	public boolean mType;
	private View content;

	private Category mCategory;
	private int mPositon;
	private ArrayList<Category> mCateList;
	protected VideoLoader mLoader;
	private BlockView mBlock;
	private static String TAG = "CategoryVideoListFragment";

	private AbsListView.OnScrollListener mOnScrollListener = new Pager(
			new Runnable() {
				@Override
				public void run() {
					if ((CategoryVideoListFragment.this.mLoader != null)
							&& (!CategoryVideoListFragment.this.mLoader.isLoading())
							&& (!CategoryVideoListFragment.this.mIsReachedBottom)) {
						// fix bug
						if(mPlayer.getYoutubePlayer() != null) if( !mPlayer.isPlaying()) draggablePanel.setVisibility(View.GONE);
						
						((VideoLoader) CategoryVideoListFragment.this.mLoader).nextPage();
						((VideoLoader) CategoryVideoListFragment.this.mLoader).forceLoad();
					}
				}
			});

	// position vua la chi so cua fragment trong mang
	// vua la id cua loader se duoc tao ra
	public void setPosition(int position) {
		mPositon = position;

	}

	public static CategoryVideoListFragment getInstance(Context context,
			ArrayList<Category> cateList, int position, DraggablePanel drpanel,VideoPlayer player) {
		return new CategoryVideoListFragment(context, cateList, position,drpanel,player);
	}

	public CategoryVideoListFragment(Context context,
			ArrayList<Category> cateList, int position, DraggablePanel drpanel,VideoPlayer player) {
		mCateList = cateList;
		mContext = context;
		mData = new ArrayList<Video>();
		mPositon = position;
		draggablePanel = drpanel;
		mPlayer = player;
	}

	public CategoryVideoListFragment(Context context,
			ArrayList<Category> cateList,VideoPlayer player) {
		mCateList = cateList;
		mContext = context;
		mData = new ArrayList<Video>();
		mPlayer = player;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mCategory = mCateList.get(mPositon);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		content = inflater.inflate(R.layout.fragment_categorylistvideo, null);
		mIsReachedBottom = false;
		if(draggablePanel == null) {
			draggablePanel = (DraggablePanel) content.findViewById(R.id.fclv_draggable_panel);
			if(mPlayer.getDraggablePanel() == null) mPlayer.setDraggablePanel(draggablePanel);
		}
		_initView(content);
		((MainActivity)getActivity()).currentFragment = this;
		return content;
	}

	private void _initView(View root) {
		// bo xu ly su kien khi click vao video tren list view
		ListView.OnItemClickListener loi = new ListView.OnItemClickListener() {@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				onVideoClick(parent, view, position, id);
			}
		};
		LinearLayout ll_root = (LinearLayout) root.findViewById(R.id.fclv_blockcontain);

		// init loader
		mLoader = new VideoLoader(mContext);
		((VideoLoader) mLoader).setType(Define.SERVICE_GET_VIDEOOFCATE);
		((VideoLoader) mLoader).setCateId(mCategory.getId());

		// init some blockview
		mBlock = new BlockView(mContext, null);
		mBlock.switchToScrollMode();

		mBlock.getList().setOnScrollListener(mOnScrollListener);
		mBlock.getLoadMore().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				VideoLoader loader = ((VideoLoader) CategoryVideoListFragment.this.mLoader);
				if (loader != null
						&& !loader.isLoading()
						&& (!CategoryVideoListFragment.this.mIsReachedBottom)) {
					loader.nextPage();
					loader.forceLoad();
				}
			}
		});
		mBlock.getList().setOnItemClickListener(loi);
		ll_root.addView(mBlock);
		
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		getLoaderManager().initLoader(CategoryVideoListFragment.this.mPositon,
				null, this);
		// xu ly nut back
		this.getView().setFocusableInTouchMode(true);
		this.getView().setOnKeyListener( new OnKeyListener(){

			@Override
		    public boolean onKey( View v, int keyCode, KeyEvent event ){
		        if( keyCode == KeyEvent.KEYCODE_BACK ){
		        	Log.i(TAG, " Back pressed");
		        	if(mPlayer!= null) if(mPlayer.mIsInitiated) if(mPlayer.getDraggablePanel()!=null) if(mPlayer.getDraggablePanel().isMaximized())  mPlayer.getDraggablePanel().minimize();
		            return true;
		        }
		        return false;
		    }
		} );
	}
	@Override
	public Loader<BaseResult> onCreateLoader(int id, Bundle arg1) {
		mLoader.setProgressNotifiable(mBlock.getLoadingView());
		return mLoader;
	}
	@Override
	public void onLoadFinished(Loader<BaseResult> loader,
			final BaseResult result) {
		// TODO Auto-generated method stub
		final int id = loader.getId();
		Log.i(TAG, "load finish:" + ((VideoLoader.Result) result).mVideo.size());
		((MainActivity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (id == CategoryVideoListFragment.this.mPositon)
					if (((VideoLoader.Result) result).mVideo.size() > 0) {
						mData = ((VideoLoader.Result) result).mVideo;
						mBlock.setData(mData);
					} else
						mIsReachedBottom = true;
			}
		});
	}
	@Override
	public void onLoaderReset(Loader<BaseResult> arg0) {
	}

	@Override
	public void refreshData() {
	}
}